<template>
  <div>
    <q-card-section>
      <p class="text-grey-6">管理系统用户，可通过分配角色获取不同页面权限。</p>
      <q-table
        :data="table.tableContentData"
        :columns="table.columns"
        :visibleColumns="table.visibleColumns"
        row-key="index"
        :loading="table.loading"
        :pagination.sync="table.initialPagination"
        @request="requestPagination"
        rows-per-page-label="每页显示"
        flat
        bordered
        :dense="$q.screen.lt.md"
        :separator="table.separator"
        :selected-rows-label="selectedRowMessage"
        selection="multiple"
        :selected.sync="table.selected"
      >
        <template v-slot:top>
          <div class="col-md-2">
            <q-select
              outlined
              dense
              v-model="form.model"
              :options="form.options"
              label="所属角色"
              clear-icon="mdi-close"
              clearable
              options-selected-class="text-primary"
              @input="getList(form.model, table.defaultPageIndex)"
            />
          </div>
          <q-space />
          <div class="col">
            <q-btn
              color="primary"
              icon="mdi-filter"
              label="更多检索条件"
              size="md"
              flat
              class="q-ml-sm"
              @click="drawerMoreFilter= !drawerMoreFilter"
            />
            <q-btn-group
              flat
              class="float-right"
            >
              <q-btn
                color="primary"
                icon="mdi-delete"
                label="批量删除"
                size="md"
                @click="getSelectedRows"
              />
              <q-btn
                color="primary"
                icon="mdi-table-row-plus-after"
                label="添加用户"
                size="md"
                @click="dialog.addRow = true"
              />
            </q-btn-group>
          </div>
        </template>
        <template v-slot:body-cell-Action="props">
          <q-td :props="props">
            <q-btn-group flat>
              <q-btn
                icon="mdi-delete"
                label="删除"
                size="sm"
                @click="getDeleteRow(props.row)"
              />
              <q-btn
                icon="mdi-table-edit"
                label="编辑"
                size="sm"
                @click="getEditRow(props.row)"
              />
            </q-btn-group>
          </q-td>
        </template>
        <template v-slot:body-cell-Status="props">
          <q-td :props="props">
            <q-toggle
              v-model="props.row.Status"
              name="Status"
              disable
            />
          </q-td>
        </template>
        <template v-slot:pagination>
          <q-pagination
            v-model="table.initialPagination.current"
            :max="table.initialPagination.page"
            :boundary-links="true"
            @click="getList(form.model, table.initialPagination.current)"
          >
          </q-pagination>
        </template>
        <template v-slot:loading>
          <q-inner-loading
            showing
            color="primary"
          />
        </template>
      </q-table>
      <!-- 对话框-删除确认 -->
      <q-dialog v-model="dialog.delConfirm">
        <q-card>
          <q-card-section class="row items-center">
            <q-avatar
              icon="mdi-alert-circle-outline"
              text-color="primary"
            />
            <span class="q-ml-sm">确定要删除所选记录吗？</span>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              flat
              label="取消"
              color="primary"
              v-close-popup
            />
            <q-btn
              flat
              label="确定删除"
              color="primary"
              v-close-popup
              @click="deleteRows(deleteID)"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
      <!-- 对话框-编辑 -->
      <q-dialog
        v-model="dialog.editConfirm"
        persistent
        @input="clearDialogForm"
      >
        <q-card style="width:400px">
          <q-card-section>
            <div class="q-pb-md text-h6">编辑用户</div>
            <q-separator />
          </q-card-section>
          <q-card-section class="row items-center">
            <q-form
              class="q-gutter-y-md full-width"
              @submit.prevent.stop="editRow"
            >
              <q-select
                outlined
                dense
                v-model="dialog.form.model"
                :options="dialog.form.options"
                label="所属角色"
                options-selected-class="text-primary"
                name="RoleID"
              />
              <q-input
                hide-bottom-space
                outlined
                v-model="dialog.form.UserName"
                label="请输入用户名"
                name="UserName"
                :rules="[val => !!val || '此项不能为空']"
              />
              <q-input
                hide-bottom-space
                outlined
                v-model="dialog.form.Password"
                label="请输入密码"
                name="Password"
                :type="dialog.form.isPwd ? 'password' : 'text'"
                hint="不修改密码请保持本项为空"
              >
                <template v-slot:append>
                  <q-icon
                    :name="dialog.form.isPwd ? 'mdi-eye-off' : 'mdi-eye'"
                    class="cursor-pointer"
                    @click="dialog.form.isPwd = !dialog.form.isPwd"
                  />
                </template>
              </q-input>
              <q-toggle
                v-model="dialog.form.Status"
                label="启用状态"
                name="Status"
                left-label
              />
              <q-input
                class="hidden"
                outlined
                dense
                readonly
                v-model="dialog.form.CreateTime"
                label="创建时间"
                name="CreateTime"
              />
              <q-input
                hide-bottom-space
                outlined
                v-model="dialog.form.ID"
                label="ID"
                name="ID"
                class="hidden"
              />

              <q-separator />
              <q-card-actions align="right">
                <q-btn
                  flat
                  label="取消"
                  color="primary"
                  v-close-popup
                />
                <q-btn
                  flat
                  label="保存"
                  color="primary"
                  v-close-popup
                  type="submit"
                />
              </q-card-actions>

            </q-form>
          </q-card-section>
        </q-card>
      </q-dialog>
      <!-- 对话框-添加 -->
      <q-dialog
        v-model="dialog.addRow"
        persistent
        @input="clearDialogForm"
      >
        <q-card style="width:400px">
          <q-card-section>
            <div class="q-pb-md text-h6">添加新用户</div>
            <q-separator />
          </q-card-section>
          <q-card-section class="row items-center">
            <q-form
              class="q-gutter-y-md full-width"
              @submit.prevent.stop="addRow"
            >
              <q-select
                outlined
                dense
                v-model="dialog.form.model"
                :options="dialog.form.options"
                label="所属角色"
                options-selected-class="text-primary"
                name="RoleID"
              />
              <q-input
                hide-bottom-space
                outlined
                v-model="dialog.form.UserName"
                label="请输入用户名"
                name="UserName"
                :rules="[val => !!val || '此项不能为空']"
              />
              <!-- <q-input
              hide-bottom-space
              outlined
              v-model="dialog.form.Password"
              label="请输入密码"
              name="Password"
              :rules="[val => !!val || '此项不能为空']"
            /> -->
              <q-input
                hide-bottom-space
                outlined
                v-model="dialog.form.Password"
                label="请输入密码"
                name="Password"
                :rules="[val => !!val || '此项不能为空']"
                :type="dialog.form.isPwd ? 'password' : 'text'"
              >
                <template v-slot:append>
                  <q-icon
                    :name="dialog.form.isPwd ? 'mdi-eye-off' : 'mdi-eye'"
                    class="cursor-pointer"
                    @click="dialog.form.isPwd = !dialog.form.isPwd"
                  />
                </template>
              </q-input>
              <q-toggle
                v-model="dialog.form.Status"
                label="启用状态"
                name="Status"
                left-label
              />
              <q-input
                class="hidden"
                outlined
                dense
                readonly
                v-model="dialog.form.CreateTime"
                label="创建时间"
                name="CreateTime"
              />
              <q-separator />
              <q-card-actions align="right">
                <q-btn
                  flat
                  label="取消"
                  color="primary"
                  v-close-popup
                />
                <q-btn
                  flat
                  label="添加"
                  color="primary"
                  v-close-popup
                  type="submit"
                />
              </q-card-actions>

            </q-form>
          </q-card-section>
        </q-card>
      </q-dialog>
    </q-card-section>
    <!-- 右侧边栏 -->
    <q-drawer
      side="right"
      v-model="drawerMoreFilter"
      overlay
      bordered
      content-class="bg-grey-1"
    >
      <q-scroll-area class="fit">
        <div class="q-pa-md">
          <p class="text-primary text-h6">检索用户
            <q-btn
              outline
              round
              icon="mdi-arrow-right"
              size="xs"
              class="float-right"
              @click="drawerMoreFilter = !drawerMoreFilter"
            />
          </p>
          <q-separator />
          <div class="q-pt-md">
            <q-form
              class="q-gutter-md"
              @submit.prevent.stop="filterSearch"
              @reset="formReset"
              ref="filterSearch"
            >
              <q-input
                outlined
                dense
                v-model="filter.UserName"
                label="用户名"
                name="UserName"
              />
              <q-select
                outlined
                dense
                v-model="filter.status.model"
                :options="filter.status.options"
                clear-icon="mdi-close"
                clearabl
                options-selected-class="text-primary"
                name="Status"
              />
              <div class="row q-col-gutter-sm">
                <div class="col">
                  <q-btn
                    label="检索"
                    color="primary"
                    unelevated
                    type="submit"
                    class="full-width"
                  />
                </div>
                <div class="col">
                  <q-btn
                    label="重置"
                    color="primary"
                    flat
                    type="reset"
                    class="full-width"
                  />
                </div>
              </div>
            </q-form>
          </div>
        </div>
      </q-scroll-area>
    </q-drawer>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'

export default {
  name: 'PageAccounts',
  components: {
  },
  props: {},
  data () {
    return {
      // 右侧边栏
      drawerMoreFilter: false,
      // ---------- 过滤检索
      filter: {
        UserName : '',
        status: {
          model: {
            label: '选择状态',
            value: -1
          },
          options:[
            {
              label: '启用',
              value: 0
            },
            {
              label: '禁用',
              value: 1
            }
          ],
        }
      },
      // ---------- 下拉框
      form: {
        model: null,
        options: [],
        RoleName: '',
      },
      // ---------- 表格
      table: {
        // 默认$Api参数
        defaultRole: -1,
        defaultPageIndex: 1,
        defaultStatus: -1,
        // 初始化分页
        initialPagination: {
          sortBy: 'desc',
          descending: false,
          page: 1,
          rowsPerPage: this.$store.state.default.rowsPerPage,
          current: 1,
          rowsNumber: 0 //if getting data from a server
        },
        // 分割线模式可选值：horizontal (default)', 'vertical', 'cell', 'none'
        separator: 'horizontal',
        loading: true,
        // 可见列
        visibleColumns: [ 'UserName', 'RoleName', 'CreateTime', 'Status',  'Action'],
        columns: [
          {
            name: 'index',
            required: true,
            label: '序号',
            align: 'center',
            field: 'index'
          },
          { name: 'ID', align: 'center', label: 'ID', field: 'ID', style: 'max-width:50px'},
          { name: 'UserName', align: 'left', label: '用户名', field: 'UserName' },
          { name: 'RoleID', align: 'left', label: '角色ID', field: 'RoleID' },
          { name: 'RoleName', align: 'left', label: '所属角色', field: 'RoleName' },
          // { name: 'CategoryName', align: 'center', label: '二级分类', field: 'CategoryName' },
          // { name: 'CategoryID', align: 'left', label: '二级分类ID', field: 'CategoryID' },
          { name: 'CreateTime', align: 'center', label: '创建时间', field: 'CreateTime' },
          // { name: 'Author', align: 'center', label: '发布者', field: 'Author' },
          { name: 'Status', align: 'center', label: '启用/禁用', field: 'Status' },
          { name: 'Action', align: 'center', label: '操作', field: '', style: 'width:220px' },
        ],
        tableContentData: [],
        selected: [],
      },
      // ---------- 对话框
      dialog: {
        delConfirm: false,
        editConfirm: false,
        editData:{},
        addRow: false,
        form: {
          model: {
            icon: '',
            label: '所属角色',
            value: 0
          },
          options: [],
          ID: '',
          UserName: '',
          Password: '',
          isPwd: true,
          Status: true,
          CreateTime: ''
        },
      },
      deleteID: []
    }
  },
  methods: {
    // 获取列表
    getList(modelValue, currentPage) {
      const _params = {
        pageIndex:currentPage,
        pageSize:this.table.initialPagination.rowsPerPage,
        RoleID:this.table.defaultRole,
        UserName: '',
        Status: this.table.defaultStatus
      }
      if (modelValue !== null) {
        _params.RoleID = modelValue.value
      }
      // console.log(params)
      this.$api.UserManageParams('', 'get', _params).then (result => {
        // console.log(result)
        this.table.tableContentData = result.data
        this.table.initialPagination.rowsNumber = result.count
        this.table.initialPagination.page = Math.ceil(this.table.initialPagination.rowsNumber / this.table.initialPagination.rowsPerPage)
        // 生成序号 & 格式化日期，去掉时间
        this.table.tableContentData.forEach((row, index) => {
          row.index = index + 1
          row.CreateTime = this.$utils.initDate(row.CreateTime, 0, 10)
        })
        // 关闭加载动画
        this.table.loading = false
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        // console.log(err)
        console.log(err.response)
      })
    },
    // 动态分页(下拉选择每页显示条数)
    requestPagination(props) {
      this.table.initialPagination.rowsPerPage = this.$utils.dynamicPagination(props)
      this.getList(this.form.model, this.table.defaultPageIndex)
    },
    // 获取分类过滤数据
    getCategory() {
      this.$api.RoleManageParams('', 'get').then (result => {
        // console.log(result)
        result.forEach((row, index) => {
          this.form.options.push({
            label : row.Name,
            value : row.ID
          })
          this.dialog.form.options.push({
            label : row.Name,
            value : row.ID
          })
        })
        // console.log(this.form.options)
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        // console.log(err)
        console.log(err.response)
      })

    },
    // 显示多条选择行数量信息
    selectedRowMessage() {
      return this.table.selected.length === 0 ? '' : `选择了全部${this.table.tableContentData.length}条记录中的${this.table.selected.length} 条`
    },
    // 获取多条选择行ID值数组
    getSelectedRows() {
      this.deleteID = []
      if (this.table.selected.length > 0) {
        this.table.selected.map((row) => {
          this.deleteID.push( row.ID)
        })
        this.dialog.delConfirm = true
      } else {
        this.$utils.notify('请选择要删除的记录','red-8')
      }
    },
    // 获取单条删除的row信息
    getDeleteRow(row) {
      this.deleteID = []
      this.deleteID.push(row.ID)
      this.dialog.delConfirm = true
    },
    // 提交服务器并删除本地预存信息
    deleteRows(rowid) {
      // 删除
      const _ids = rowid
      this.$api.UserManageData('', 'delete', _ids).then (result => {
        // console.log(result)
         if ( result === 'success') {
          //  重新请求数据列表
           this.getList(this.form.model, this.table.defaultPageIndex)
         } else if ( result === 'error' ) {
           this.$utils.notify('数据库操作错误，请联系管理员', 'red-8')
         } else {
           this.$utils.notify(result, 'red-8')
         }
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })
      this.deleteID = []
      this.table.selected = []
    },
    // 获得编辑的行数据
    getEditRow(value) {
      this.dialog.editConfirm = true
      // console.log(value)
      this.dialog.form.model.label = value.RoleName
      this.dialog.form.model.value = value.RoleID
      this.dialog.form.RoleName = value.RoleName
      this.dialog.form.ID = value.ID
      this.dialog.form.UserName = value.UserName
      this.dialog.form.Password = value.Password
      this.dialog.form.Status = value.Status
      this.dialog.form.CreateTime = value.CreateTime
    },
    // 提交编辑数据
    editRow (evt) {
      this.editRowResult = this.$utils.formatFormData(evt)
      delete this.editRowResult.ID
      // console.log(this.editRowResult)
      
      this.$api.UserManageData(this.dialog.form.ID, 'put', this.editRowResult).then (result => {
        // console.log(result)
         if ( result === 'success') {
          this.clearDialogForm()
          this.$utils.notify('数据修改成功！', 'positive')
          // 重新请求数据列表
          this.getList(this.form.model, this.table.defaultPageIndex)
         } else if ( result === 'error' ) {
           this.$utils.notify('数据库操作错误，请联系管理员', 'red-8')
         } else if ( result === 'exist' ) {
           this.$utils.notify('用户名已存在', 'red-10')
         } else {
           this.$utils.notify(result, 'red-8')
         }
      }).catch (err => {
        console.log(err)
      })
    },
    // 获取当前时间，给创建时间赋值
    getDateNow() {
      this.dialog.form.CreateTime = this.$utils.initDate(Date.now(), 0, 10)
    },
    // 添加新行
    addRow(evt) {
      this.addRowResult = this.$utils.formatFormData(evt)
      // console.log(this.addRowResult)
      
      this.$api.UserManageData('', 'post', this.addRowResult).then (result => {
        if ( result === 'success') {
          this.clearDialogForm()
        //  重新请求数据列表
          this.getList(this.form.model, this.table.defaultPageIndex)
        } else if ( result === 'error' ) {
          this.$utils.notify('数据库操作错误，请联系管理员', 'red-8')
        } else if ( result === 'exist' ) {
          this.$utils.notify('该用户已存在', 'red-8')
        } else {
           this.$utils.notify(result, 'red-8')
         }
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })
    },
    // 过滤检索
    // 提交检索
    filterSearch(evt) {
      const _filterResult = this.$utils.formatFormData(evt)
      _filterResult.pageIndex = this.table.defaultPageIndex
      _filterResult.pageSize = this.table.initialPagination.rowsPerPage
      _filterResult.RoleID = this.table.defaultRole,
      // console.log(_filterResult)
      this.$api.UserManageParams('', 'get', _filterResult).then( result => {
        // console.log(result)
        this.table.tableContentData = result.data
        this.table.initialPagination.rowsNumber = result.count
        this.table.initialPagination.page = Math.ceil(this.table.initialPagination.rowsNumber / this.table.initialPagination.rowsPerPage)
        // 生成序号 & 格式化日期，去掉时间
        this.table.tableContentData.forEach((row, index) => {
          row.index = index + 1
          row.CreateTime = this.$utils.initDate(row.CreateTime, 0, 10)
        })
        // 关闭加载动画
        this.table.loading = false
      }).catch(err => {
        console.log(err)
      })
    },
    // 重置搜索条件
    formReset() {
      const _defaultOptions = [
        {
          label: '启用',
          value: 0
        },
        {
          label: '禁用',
          value: 1
        }
      ]
      this.filter.UserName = ''
      this.filter.status.model.label = '选择状态'
      this.filter.status.model.value = -1
      this.filter.status.options = _defaultOptions
      this.getList(this.form.model, this.table.defaultPageIndex)
      // console.log(this.filter)
    },
    // 清除表单内容
    clearDialogForm() {
        this.dialog.form.model.icon = ''
        this.dialog.form.model.label = '选择角色'
        this.dialog.form.model.value = 0
        this.dialog.form.RoleName = ''
        this.dialog.form.id = ''
        this.dialog.form.UserName = ''
        this.dialog.form.Password = ''
        this.dialog.form.Status = true
        this.dialog.form.CreateTime = ''
        this.dialog.form.isPwd = true
        this.getCategory()
    },

    // session过期操作
    ...mapMutations(['changeLogin']),
    unauthorized() {
      // 弹出警告框
      this.$utils.notify('身份信息过期','red-8')
      // 清除vuex中的token
      this.changeLogin({ Authorization: '' })
      // 路由跳转
      this.$router.push('/Login', onComplete => {}, onAbort => {});
    }
  },
  mounted() {
    this.getList(this.form.model, this.table.defaultPageIndex)
    this.clearDialogForm()
    this.getDateNow()
  },
}
</script>
<style>
.q-pagination .q-btn__wrapper:before {
  box-shadow: none;
}
.q-table th,
.q-table td {
  padding: 7px 10px;
  background-color: inherit;
}
</style>